<template>
  <el-dialog
    v-model="isVisible"
    :close-on-click-modal="false"
    :title="title"
    :type="type"
    :modal-append-to-body="false"
    :center="true"
    width="800px"
    top="50px"
    class="dialog-wrap"
  >
    <el-form
      ref="formRef"
      class="dialog-from"
      :model="form"
      label-width="75px"
    >
      <el-form-item label="方案名称">
        <el-input
          v-model="form.logisticsName"
          maxlength="20"
          :disabled="isDisabled"
          onblur="value=value.replace(/(^\s*)|(\s*$)/g, '')"
        />
      </el-form-item>
      <el-form-item label="计费方式">
        <el-radio-group v-model="form.chargeType">
          <el-radio :disabled="isDisabled" :label="1">按件数</el-radio>
          <el-radio :disabled="isDisabled" :label="2">按重量</el-radio>
          <el-radio :disabled="isDisabled" :label="3">包邮</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.charges && form.charges.length">
        <div
          v-for="(logisticsDetail, index) in form.charges"
          :key="index"
          class="delivery-area-item"
        >
          <el-icon v-if="!isDisabled" class="delect-area" @click="deleteLogistics(index)"><el-icon-delete /></el-icon>
          <el-form-item class="margin-bottom-0" label="配送区域">
            <div
              class="add-area-btn text-overflow"
              :class="isDisabled ? 'disabled' : ''"
              :title="
                logisticsDetail.regions && logisticsDetail.regions.toString()
              "
              @click="openAreaDialog(index)"
            >
              {{
                (logisticsDetail.regions &&
                  logisticsDetail.regions.length &&
                  logisticsDetail.regions.toString()) ||
                  '请选择'
              }}
            </div>
          </el-form-item>
          <el-form-item v-if="form.chargeType !== 3" label="计费明细">
            <div class="form-item-row">
              <div class="el-row" style="margin-bottom: 10px">
                首重/件费用 &nbsp;&nbsp;&nbsp;&nbsp;
                <el-input-number
                  v-model="logisticsDetail.weight"
                  :disabled="isDisabled"
                  :controls="false"
                  :max="999"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                />
                <!-- <el-input
                    v-model="logisticsDetail.weight"
                    maxlength="9"
                    :readonly="isDisabled"
                    placeholder="请输入内容"
                    oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  /> -->
                KG/件
                <el-input-number
                  v-model="logisticsDetail.price"
                  :disabled="isDisabled"
                  :controls="false"
                  :max="999999999"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                />
                <!-- <el-input
                    v-model="logisticsDetail.price"
                    maxlength="9"
                    type="text"
                    :readonly="isDisabled"
                    placeholder="请输入内容"
                    oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  /> -->
                元
              </div>
              <div class="el-row">
                续重/件费用 每
                <el-input-number
                  v-model="logisticsDetail.secondWeight"
                  :disabled="isDisabled"
                  :controls="false"
                  :max="999"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                />
                <!-- <el-input
                    v-model="logisticsDetail.secondWeight"
                    maxlength="9"
                    :readonly="isDisabled"
                    placeholder="请输入内容"
                    oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  /> -->
                KG/件
                <el-input-number
                  v-model="logisticsDetail.secondPrice"
                  :disabled="isDisabled"
                  :controls="false"
                  :max="999999999"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                />
                <!-- <el-input
                    v-model="logisticsDetail.secondPrice"
                    maxlength="9"
                    :readonly="isDisabled"
                    placeholder="请输入内容"
                    oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  /> -->
                元
              </div>
            </div>
          </el-form-item>
        </div>
      </template>
    </el-form>
    <div v-if="form.chargeType !== 3" class="delivery-area-btn">
      <el-button
        v-if="!isDisabled"
        type="primary"
        @click="addArea"
      >继续添加区域</el-button>
    </div>
    <div v-if="!isDisabled" class="btn-wrap">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确定</el-button>
      <el-button @click="isVisible = false">取消</el-button>
    </div>
    <el-dialog
      v-model="visible.area"
      width="60%"
      title="选择配送区域"
      class="address-dialog"
      append-to-body
    >
      <div class="area-dialog">
        <el-row>
          <template v-for="(province, index) in areaList">
            <el-col
              v-if="province.list.length > 0"
              :key="index"
              class="province-wrap"
              :span="8"
            >
              <el-checkbox
                v-model="province.selected"
                :label="province.provinceName"
                @change="checkboxChange(province.keyId, province.selected)"
              />
              <el-cascader
                v-model="province.selectCity"
                :options="province.list"
                :props="{
                  multiple: true,
                  children: 'list',
                  label: 'city',
                  value: 'city',
                }"
                collapse-tags
                filterable
                @change="changeCity(province)"
              />
            </el-col>
          </template>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="visible.area = false">取 消</el-button>
        <el-button type="primary" @click="getSelectData">确 定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { defineComponent, computed, reactive, ref, shallowRef, toRefs } from 'vue'

import { Delete as ElIconDelete } from '@element-plus/icons-vue'
// import Setting from "@/api/Setting";
import { logisticsGetById, logisticsAdd, logisticsUpdate } from '@/api/shopSys'
import areaJSON from '@/assets/area'

defineComponent({
  name: 'LogisticsForm'
})

const props = defineProps({
  type: {
    type: String,
    default: 'add',
  },
})

const { type } = toRefs(props);

const emits = defineEmits(['success'])
const btnLoading = ref(false)
const isVisible = shallowRef(false);

const isDisabled = computed(() => type.value === 'check')
const title = computed(() => {
  const titleMap = {
    add: '新建方案',
    check: '查看方案',
    edit: '修改方案',
  }
  return titleMap[type.value]
})

const form = ref({
  logisticsName: '',
  chargeType: 1,
  charges: [
    {
      weight: 0,
      price: 0,
      secondWeight: 0,
      secondPrice: 0,
      regions: [],
    },
  ],
})

const checkId = ref(null);
const areaList = ref([]);
const areaFilter = ref([]);
const currentSelectCity = ref([]);
const currentAreaIndex = shallowRef(0);
const visible = reactive({
  area: false,
})

// 初始化地区
function initArea () {
  const { province_list, city_list } = areaJSON
  const provinceKeys = Object.keys(province_list)
  const cityKeys = Object.keys(city_list)
  areaList.value = provinceKeys.map((provinceKey) => {
    provinceKey += ''
    let provinceList = []
    const provinceKeyId = provinceKey.slice(0, 2)
    const provinceName = province_list[provinceKey]
    let provinceSelected = false
    cityKeys.map((cityKey) => {
      const cityKeyId = cityKey.slice(0, 2)
      const cityName = city_list[cityKey]
      if (
        provinceKeyId === cityKeyId &&
            areaFilter.value.indexOf(cityName) === -1
      ) {
        provinceList.push({
          id: cityKey,
          selected: false,
          city: cityName,
        })
      }
    })
    // 回显
    let selectCity = []
    if (currentSelectCity.value.indexOf(provinceName) > -1) {
      selectCity = provinceList.map((cityItem) => {
        return [cityItem.city]
      })
      provinceSelected = true
    } else {
      provinceList.map((cityItem) => {
        if (currentSelectCity.value.indexOf(cityItem.city) > -1) {
          selectCity.push([cityItem.city])
        }
      })
    }
    if (areaFilter.value.indexOf(provinceName) > -1) {
      provinceList = []
    }
    return {
      selectCity: selectCity,
      keyId: provinceKeyId,
      selected: provinceSelected,
      provinceName: provinceName,
      list: provinceList,
    }
  })
}
function changeCity (item) {
  if (item.selectCity.length !== 0) {
    if (!item.selected) {
      item.selected = true
    }
  } else {
    item.selected = false
  }
}
// 全选省级
function checkboxChange (provincekeyId, selected) {
  areaList.value.map((item) => {
    const { keyId, list } = item
    const allCity = list.map((cityItem) => {
      const { city } = cityItem
      return [city]
    })
    if (keyId === provincekeyId && selected) {
      item.selectCity = allCity
    }
    if (keyId === provincekeyId && !selected) {
      item.selectCity = []
    }
    return item
  })
}
function reset () {
  form.value = {
    logisticsName: '',
    chargeType: 1,
    chargingWay: 0,
    charges: [
      {
        weight: 0,
        price: 0,
        secondWeight: 0,
        secondPrice: 0,
        regions: [],
      },
    ],
  }
}
// 添加地区
function addArea () {
  form.value.charges.push({
    weight: 0,
    price: 0,
    secondWeight: 0,
    secondPrice: 0,
    regions: [],
  })
}

// 删除地区
function deleteLogistics (index) {
  form.value.charges.splice(index, 1)
}

// 打开选择地区弹框
function openAreaDialog (index) {
  if (type.value === 'check') {
    return false
  }
  visible.area = true
  currentAreaIndex.value = index
  // 获取已选择的城市
  areaFilter.value = []
  currentSelectCity.value = []
  form.value.charges.map((logisticsDetail, logisticsDetailIndex) => {
    // 获取其他可配送区域已选的城市
    const { regions } = logisticsDetail || ''

    if (index !== logisticsDetailIndex) {
      regions.map((region) => {
        if (region.indexOf('-') > -1) {
          const regionSplit = region.split('-')
          const province = regionSplit[0]
          const citys = regionSplit[1] && regionSplit[1].split(',')
          if (province) {
            if (citys) {
              areaFilter.value = areaFilter.value.concat(citys)
            }
          }
        } else {
          areaFilter.value.push(region)
        }
      })
    } else {
      regions.map((region) => {
        if (region.indexOf(':') > -1) {
          const regionSplit = region.split(':')
          const province = regionSplit[0]
          const citys = regionSplit[1] && regionSplit[1].split(',')
          if (province) {
            if (citys) {
              currentSelectCity.value = currentSelectCity.value.concat(citys)
            }
          }
        } else {
          currentSelectCity.value.push(region)
        }
      })
    }
  })
  initArea()
}

function getSelectData () {
  const selectedArea = getSelectedArea()
  form.value.charges[currentAreaIndex.value].regions = selectedArea
  visible.area = false
}

// 获取选择的地区
function getSelectedArea () {
  const selectAddressList = []
  areaList.value.map((areaItem) => {
    const { selectCity, provinceName, list } = areaItem
    const citys = selectCity.map((city) => {
      return city[0]
    })
    if (selectCity.length) {
      // 判断是否全选，全选就直接获取省级
      if (selectCity.length === list.length) {
        selectAddressList.push(provinceName)
      } else {
        const addressStr = provinceName + ':' + citys.toString()
        selectAddressList.push(addressStr)
      }
    }
  })
  return selectAddressList
}

// 查看详情
function getDetails () {
  logisticsGetById({ logisticsId: checkId.value }).then(res => {
    if (res.code === '') {
      form.value = res.data
    }
  })
}
function onSubmit () {
  if (form.value.logisticsName === '') {
    ElMessage.error('请输入方案名称')
  } else if (type.value === 'add') {
    add()
  } else if (type.value === 'edit') {
    update()
  } else {
    isVisible.value = false
  }
}
function add () {
  btnLoading.value = true
  logisticsAdd(form.value).then(res => {
    if (res.code === '') {
      isVisible.value = false
      ElMessage.success('成功添加')
      emits('success')
    }
  }).finally(() => {
    btnLoading.value = false
  })
}
function update () {
  btnLoading.value = true
  logisticsUpdate(form.value).then(res => {
    if (res.code === '') {
      isVisible.value = false
      ElMessage.success('成功')
      emits('success')
    }
  }).finally(() => {
    btnLoading.value = false
  })
}

function open (val) {
  isVisible.value = true
  if (val) {
    setParams(val)
  } else {
    reset()
  }
}

function setParams (val = {}) {
  if (val['params']) {
    form.value = val['params']
  }
  if (val['checkId']) {
    checkId.value = val['checkId']
    getDetails()
  }
}

defineExpose({
  open,
})

</script>

<style lang="scss" scoped>
.dialog-wrap {
  :deep(.el-dialog) {
    display: flex;
    flex-direction: column;
    max-height: 80vh;
    max-width: 900px;
    overflow: hidden;

    .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  }

  // .dialog-from {
  //   width: 80%;
  //   margin: auto;
  // }

  .btn-wrap {
    margin: 45px auto 0;
    text-align: center;
  }

  .form-item-row {
    // padding-top: 40px;
    :deep(.el-input,.el-input-number) {
      width: 135px;
      margin: 0 5px;
    }
  }
}

.delivery-area-item {
  position: relative;
  padding: 30px;
  background-color: #f7f8fa;
  // border-bottom: 2px solid #fff;
  margin-bottom: 10px;

  .margin-bottom-0 {
    margin-bottom: 0px;
  }

  .delect-area {
    position: absolute;
    top: 15px;
    right: 15px;
    font-size: 20px;
    z-index: 999;
    cursor: pointer;
  }

  .add-area-btn {
    overflow: hidden;
    color: #3A68F2;
    cursor: pointer;

    &.disabled {
      color: #c0c4cc;
    }
  }
}

.delivery-area-btn {
  margin: 15px auto;
  // text-align: center;
}

.address-dialog {
  .province-wrap {
    position: relative;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    // 重写el-cascader样式
    :deep(.el-cascader) {
      // width: 100% !important;
      line-height: normal;
      .el-input__wrapper {
        box-shadow: none;
      }
      .el-input {
        cursor: pointer;
        width: 100% !important;
        height: 28px !important;

        span.el-input__suffix {
          position: inherit !important;

          i.el-input__icon {
            line-height: inherit;
            margin-left: 5px;
          }
        }
      }

      input,
      .el-cascader__tags {
        display: none !important;
      }
    }
  }
}
:deep(.el-form-item__label) {
  font-weight: bold;
}
</style>
